<template>
  <div class="contract-invoice">
    <s-table
      bordered
      ref="table"
      size="middle"
      :row-key="(record) => record.id"
      :columns="invoiceColumns"
      :data="invoiceData"
    >
      <template slot="title">
        <a-button size="small" icon="plus" type="primary" @click="addInvoice">添加发票</a-button>
      </template>
      <template slot="invoice_type" slot-scope="text">
        {{ typeOpts[text] }}
      </template>
      <template slot="header_type" slot-scope="text">
        {{ headerOpts[text] }}
      </template>
      <template slot="amount" slot-scope="text">
        <a-tag color="red">{{ text }}</a-tag>
      </template>
      <template slot="invoice_fee" slot-scope="text">
        <a-tag color="red">{{ text }}</a-tag>
      </template>
      <template slot="status" slot-scope="text">
        <a-tag color="red">{{ statusOpts[text] }}</a-tag>
      </template>
      <template slot="express" slot-scope="text, record">
        <div v-if="record.express_name">{{ record.express_name }}({{ record.express_num }})</div>
      </template>
      <template slot="action" slot-scope="text,record">
        <a-badge dot v-if="record.is_read == 0">
          <a-button size="small" type="primary" @click="toDetail(record.id)">查看</a-button>
        </a-badge>
        <a-button v-else size="small" type="primary" @click="toDetail(record.id)">查看</a-button>
        <div style="display: inline-block; margin-left: 5px;" v-if="record.status == 30 || record.status == 50"><a-button size="small" type="danger" @click="editInvoice(record.id)">重新开票</a-button></div>
      </template>
    </s-table>
    <a-modal
      destroy-on-close
      title="填写发票信息"
      v-model="invoiceVisible"
      :width="700"
      :mask-closable="false"
      @ok="onSubmit"
    >
      <a-form-model
        ref="ruleForm"
        :model="invoiceForm"
        :rules="invoiceRules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol"
      >
        <a-form-model-item label="选择开票公司" prop="company_id">
          <a-select
            show-search
            placeholder="选择开票公司"
            v-model="invoiceForm.company_id"
            :filter-option="filterOption"
            @change="onChange"
          >
            <a-select-option :disabled="item.stock == 0" v-for="item in companyOpts" :key="item.id" :value="item.id">{{ item.company_name }}({{ item.tax_point }}%)({{ item.stock }})</a-select-option>
          </a-select>
        </a-form-model-item>
        <a-divider orientation="left">填写纳税人信息</a-divider>
        <a-form-model-item label="开票附件" prop="file_url">
          <a-upload
            accept=".docx,.doc"
            name="file"
            :multiple="true"
            :action="uploadUrl"
            :headers="header"
            @change="uploadChange"
          >
            <a-button> <a-icon type="upload" />附件</a-button>
            <a-button size="small" type="link" icon="download" @click="download">点击下载发票模版</a-button>
          </a-upload>
        </a-form-model-item>
<!--        <a-form-model-item label="抬头类型" prop="header_type">-->
<!--          <a-radio-group v-model="invoiceForm.header_type">-->
<!--            <a-radio v-for="(item,index) in headerOpts" :key="index" :value="index">-->
<!--              {{ item }}-->
<!--            </a-radio>-->
<!--          </a-radio-group>-->
<!--        </a-form-model-item>-->
<!--        <a-form-model-item label="发票抬头" prop="header">-->
<!--          &lt;!&ndash;          <template slot="help">&ndash;&gt;-->
<!--          &lt;!&ndash;            <span style="color:#999">无需填写，与合同基本信息一致</span>&ndash;&gt;-->
<!--          &lt;!&ndash;          </template>&ndash;&gt;-->
<!--          <a-input v-model="invoiceForm.header" placeholder="输入发票抬头" />-->
<!--        </a-form-model-item>-->
<!--        <a-form-model-item label="发票类型" prop="invoice_type">-->
<!--          <template slot="help">-->
<!--            <span style="color:#999">无需填写，选择开票时自动选择</span>-->
<!--          </template>-->
<!--          <a-radio-group disabled v-model="invoiceForm.invoice_type" name="radioGroup">-->
<!--            <a-radio v-for="(item,index) in typeOpts" :key="index" :value="index">{{ item }}</a-radio>-->
<!--          </a-radio-group>-->
<!--        </a-form-model-item>-->
<!--        <a-form-model-item label="统一社会信用代码" prop="social_code">-->
<!--          <a-input v-model="invoiceForm.social_code" placeholder="输入统一社会信用代码" />-->
<!--        </a-form-model-item>-->
<!--        <a-form-model-item label="开户银行名称" prop="bank_name">-->
<!--          <a-input v-model="invoiceForm.bank_name" placeholder="输入开户银行名称" />-->
<!--        </a-form-model-item>-->
<!--        <a-form-model-item label="基本开户账号" prop="account_num">-->
<!--          <a-input v-model="invoiceForm.account_num" placeholder="输入基本开户账号" />-->
<!--        </a-form-model-item>-->
<!--        <a-form-model-item label="注册场所地址" prop="register_address">-->
<!--          <a-input v-model="invoiceForm.register_address" placeholder="输入注册场所地址" />-->
<!--        </a-form-model-item>-->
<!--        <a-form-model-item label="注册固定电话" prop="register_phone">-->
<!--          <a-input v-model="invoiceForm.register_phone" placeholder="输入注册固定电话" />-->
<!--        </a-form-model-item>-->
        <a-form-model-item label="申请备注" prop="notes">
          <a-textarea v-model="invoiceForm.notes" placeholder="输入申请备注"></a-textarea>
        </a-form-model-item>
      </a-form-model>
    </a-modal>
  </div>
</template>

<script>
import { STable } from '@/components'
import contractColumns from '@/columns/contract'
import { SetInvoiceRead } from '@/api/invoice'
import { getAddInvoice, getInvoiceList, postAddInvoice, getEditInvoice, postEditInvoice } from '@/api/contract'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import apis from '@/api'

export default {
  components: {
    STable
  },
  name: 'Invoice',
  data () {
    const validateUrl = (rule, value, callback) => {
      if (value === '') {
        return callback(new Error('必须上传发票模版'))
      } else {
        callback()
      }
    }
    return {
      labelCol: { span: 8 },
      wrapperCol: { span: 12 },
      invoiceColumns: contractColumns.invoice,
      invoiceData: parameters => {
        return getInvoiceList(Object.assign(parameters, this.queryParam)).then(res => {
          this.typeOpts = res.result.invoiceTypeOpts
          this.headerOpts = res.result.headerTypeOpts
          this.statusOpts = res.result.invoiceStatusOpts
          return res.result
        })
      },
      invoiceForm: {},
      invoiceVisible: false,
      typeOpts: {},
      headerOpts: {},
      companyOpts: {},
      invoiceRules: {
        company_id: [{ required: true, message: '必须选择开票公司', trigger: 'change' }],
        file_url: [{ validator: validateUrl, trigger: 'change' }]
      },
      // invoiceRules1: {
      //   company_id: [{ required: true, message: '必须选择开票公司', trigger: 'change' }],
      //   header_type: [{ required: true, message: '必须选择抬头类型', trigger: 'change' }],
      //   header: [{ required: true, message: '必须填写发票抬头', trigger: 'blur' }],
      //   invoice_type: [{ required: true, message: '必须选择发票类型', trigger: 'change' }],
      //   social_code: [{ required: true, message: '必须填写统一信用代码证', trigger: 'blur' }]
      // },
      // invoiceRules2: {
      //   company_id: [{ required: true, message: '必须选择开票公司', trigger: 'change' }],
      //   header_type: [{ required: true, message: '必须选择抬头类型', trigger: 'change' }],
      //   header: [{ required: true, message: '必须填写发票抬头', trigger: 'blur' }],
      //   invoice_type: [{ required: true, message: '必须选择发票类型', trigger: 'change' }],
      //   bank_name: [{ required: true, message: '必须填写开户行', trigger: 'blur' }],
      //   social_code: [{ required: true, message: '必须填写统一信用代码证', trigger: 'blur' }],
      //   account_num: [{ required: true, message: '必须填写银行账户', trigger: 'blur' }],
      //   register_address: [{ required: true, message: '必须填写地址', trigger: 'blur' }],
      //   register_phone: [{ required: true, message: '必须填写联系电话', trigger: 'blur' }]
      // },
      queryParam: {},
      statusOpts: {},
      header: {
        'Access-Token': storage.get(ACCESS_TOKEN)
      },
      uploadUrl: apis.Upload
    }
  },
  created () {
    this.queryParam['filter[contract_id]'] = this.$route.params.cid
  },
  methods: {
    addInvoice () {
      const app = this
      const parameter = {}
      app.invoiceForm = {}
      parameter['contract_id'] = app.$route.params.cid
      app.invoiceForm['contract_id'] = app.$route.params.cid
      getAddInvoice(parameter).then(res => {
        app.invoiceForm.header = res.result.subject
        app.companyOpts = res.result.company_data
        app.headerOpts = res.result.header_type_opts
        app.typeOpts = res.result.invoice_type_opts
        app.invoiceVisible = true
      })
    },
    editInvoice (id) {
      getEditInvoice(id).then(res => {
        this.invoiceForm = res.result.invoiceData
        this.invoiceForm.invoice_id = id
        this.companyOpts = res.result.company_data
        this.invoiceVisible = true
      })
    },
    onSubmit () {
      const app = this
      const parameter = {}
      const data = {}
      parameter['contract_id'] = app.$route.params.cid
      app.$refs.ruleForm.validate(valid => {
        if (valid) {
          for (const k in app.invoiceForm) {
            data['invoice[' + k + ']'] = app.invoiceForm[k]
          }
          // data['contract_id'] = app.$route.params.cid
          if (app.invoiceForm.invoice_id) {
            postEditInvoice(data, this.invoiceForm.invoice_id).then(res => {
              if (res.status === 0) {
                app.invoiceVisible = false
                app.$refs.table.refresh(true)
              } else {
                app.$warning({
                  title: res.msg
                })
              }
            })
          } else {
            postAddInvoice(data, parameter).then(res => {
              if (res.status === 0) {
                app.invoiceVisible = false
                app.$refs.table.refresh(true)
              } else {
                app.$warning({
                  title: res.msg
                })
              }
            })
          }
        } else {
          return false
        }
      })
    },
    onChange (value) {
      const type = this.companyOpts.find(event => event.id === value)
      this.invoiceForm.invoice_type = type.invoice_type.toString()
      this.invoiceForm.company_id = value
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    uploadChange (info) {
      if (info.file.status === 'done') {
        this.invoiceForm['file_url'] = info.file.response.result.url
        this.invoiceForm['filename'] = info.file.name
      }
    },
    toDetail (id) {
      this.$router.push({ name: 'InvoiceDetail', params: { id } })
      SetInvoiceRead(id)
      this.$refs.table.refresh(true)
    },
    download () {
      window.open('https://design-upload.oss-cn-beijing.aliyuncs.com/template.docx')
    }
  }
}
</script>

<style scoped>

</style>
